package com.yc.dygang.dao;

import com.yc.common.util.DBHelper;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class CategoryDao {

    private static JedisPool jedisPool;
    static {
        try {
            jedisPool = new JedisPool("127.0.0.1",6379);
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("Redis服务器未启动");
        }
    }
    public List<Map<String, Object>> queryCategory1(){
        Jedis jedis = jedisPool.getResource();
        //获取缓存的分类数据
        List<String> categoryList = jedis.lrange("categoryList", 0, -1);
        List<Map<String,Object>> list;
        if (categoryList == null || categoryList.isEmpty()){
            //如果Redis 没有缓存数据
            String sql = "select * from dyg_category" ;
            list = DBHelper.selectListMap(sql);
            //将数据写入Redis
            for (Map<String, Object> category : list) {
                category.forEach((key,value) ->{
                    jedis.hset("cmap_"+category.get("id"),key,value.toString());
                });
                jedis.lpush("categoryList",category.get("id").toString());
            }
            return list;
        }else {
            list = new ArrayList<>();
            for (String id : categoryList) {
                String key = "cmap_"+id;
                Map<String, String> category = jedis.hgetAll(key);
                HashMap<String,Object> c= new HashMap<>();
                category.forEach((k,value) ->{
                    c.put(k,value);
                });
                list.add(c);
            }
            return list;
        }
    }

    public Map<String, Object> queryCategory(String id){
        String sql = "select * from dyg_category where id=?" ;
        Map<String, Object> map = DBHelper.selectOneMap(sql,id);
        return map;
    }
}
